package vip.xiaonuo.redis;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import vip.xiaonuo.redis.model.DayInfo;
import vip.xiaonuo.redis.model.DayInfoReturnData;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class DayInfoService {
    @Resource
    private RedissonClient client;

    public final String DAY_INFO_PRE = "DAY_INFO_";

    private String request_url = "http://apis.juhe.cn/fapig/calendar/day.php?key=[KEY]&date=[DATE]";

    private final String request_key = "671101c2532bd2adf5acdbd35c7f89e0";

    public boolean nextDayIsWorkDay(String date){
        String key = DAY_INFO_PRE + "MAP";
        RBucket<Map<String,DayInfo>> bucketMap = client.getBucket(key);
        Map<String,DayInfo> dayInfoMap = new LinkedHashMap<>();
        if(bucketMap.isExists()){
            dayInfoMap = bucketMap.get();
        }

        if(!dayInfoMap.containsKey(date)){
            DayInfo info = this.netQuery(date);
            dayInfoMap.put(date,info);
            bucketMap.set(dayInfoMap);
        }

        DayInfo info = dayInfoMap.get(date);
        return "工作日".equals(info.getStatusDesc());
    }

    private DayInfo netQuery(String date){
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("text/plain");
        // RequestBody body = RequestBody.create(mediaType, "");
        String url = request_url.replace("[KEY]",request_key).replace("[DATE]",date);
        Request request = new Request.Builder().url(url).method("GET",null)
//                .addHeader("Cookie", "aliyungf_tc=8b0e739a1f404ff664b06ec343d10f3f667208718aced590712d5eccaf65bd67")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String msg = response.body().string();
            log.info("网络请求返回结果：" , msg);
            DayInfoReturnData data = JSON.parseObject(msg, DayInfoReturnData.class);
            DayInfo info = data.getResult() == null ? new DayInfo() : data.getResult();
            info.setReason(data.getReason());
            info.setError_code(data.getError_code());
            return info;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DayInfo.error();
    }

}
